import { createStore } from 'vuex'
import defaultReport from '@/models/healthReport'
import useReport from '@/hooks/useReport'
import HealthReportApi from '@/api/report'

export default createStore({
  state: {
    healthReport: JSON.stringify(defaultReport)
  },
  mutations: {
    setData(state, value) {
      state.healthReport = value
    }
  },
  actions: {
    // 获取健康报告
    getHealthReport(context, value) {
      return new Promise((resolve, reject) => {
        HealthReportApi.getHealthReport({
          id: value.id,
          sn: value.sn,
          timestamp: value.timestamp,
          auth: value.auth,
          idCardNo: value.idCardNo
        })
          .then((res) => {
            if (res.success === true) {
              let healthReport = defaultReport
              let { filterData } = useReport() // null过滤
              for (const key in res.data) {
                if (res.data[key] && res.data[key] !== null) {
                  healthReport[key] = res.data[key]
                  filterData(
                    healthReport[key],
                    res.data[key],
                    defaultReport[key]
                  )
                } else {
                  healthReport[key] = defaultReport[key] // 设置默认值
                }
              }
              context.commit('setData', JSON.stringify(healthReport))
              resolve(healthReport)
            } else {
              reject(res)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  },
  modules: {}
})
